<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button v-if="activeKey=='cg'"@click="handleAdd" type="primary" icon="plus">添加</a-button>
      <a-button v-if="activeKey=='cg'"@click="openButton('isProduction','0')" type="danger" ghost icon="close">关闭</a-button>

      <a-button v-if="activeKey=='approved'"@click="openPlanButton('onOff','1')" type="primary" icon="check">开启</a-button>
      <a-button v-if="activeKey=='approved'"@click="openPlanButton('onOff','0')" type="danger" ghost icon="close">关闭</a-button>
<!--      <a-button type="primary" icon="download" @click="handleExportXls('生产计划单')">导出</a-button>-->
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>-->
      <!-- 高级查询区域 -->
<!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-tabs v-model="activeKey" @change="handleChangeTab">
        <a-tab-pane key="cg" tab="未生成">
          <div>
            <a-table
              ref="procTable"
              size="middle"
              bordered
              rowKey="id"
              class="j-table-force-nowrap1"
              :scroll="{ x: true }"
              :columns="table1.columns"
              :dataSource="table1.dataSource"
              :pagination="table1.ipagination"
              :loading="table1.loading"
              @change="handleTableChange1"
              :rowSelection="{  selectedRowKeys: table1.selectedRowKeys, onChange: onSelectChangeTab1 }"
            >

            </a-table>
          </div>
        </a-tab-pane>
        <a-tab-pane key="notGenerated" tab="暂存中" force-render>
          <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="detailId"
        class="j-table-force-nowrap1"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.status < 0" @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
           <act-apply-btn
             @success="handleChangeTab"
             :data-id="record.id"
             :serviceName="serviceName"
             :variables="record"
           ></act-apply-btn>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
        </a-tab-pane>
        <a-tab-pane key="needEdit" tab="需修改" force-render>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="detailId"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="action" slot-scope="text, record">
           <a v-if="record.status < 0" @click="handleEdit(record)">编辑</a>
                <a-divider v-if="record.status < 0"  type="vertical" />
              <act-apply-btn
                v-show="record.actStatus == '撤回'"
                @success="handleChangeTab"
                :data-id="record.id"
                :serviceName="serviceName"
                :variables="record"
              ></act-apply-btn>
              <a-popconfirm  v-if="record.actStatus != '撤回'" title="确定取消申请吗?" @confirm="() => handleStop(record)">
               <a href="javascript:;">取消申请</a>
              </a-popconfirm>
              <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
              <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
          <a-divider type="vertical" />
               <a @click="handleDetail(record)">详情</a>
        </span>

          </a-table>
        </a-tab-pane>
        <a-tab-pane key="approving" tab="审核中"  force-render>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="detailId"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="action" slot-scope="text, record">

      <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
          <a-divider type="vertical" />
         <a @click="handleDetail(record)">详情</a>
           <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
              <a-popconfirm  v-if="record.actStatus != '撤回'" title="确定取消申请吗?" @confirm="() => handleStop(record)">
               <a href="javascript:;">取消申请</a>
              </a-popconfirm>
<!--          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>-->
        </span>

          </a-table>
        </a-tab-pane>
        <a-tab-pane key="approved" tab="已审批"  force-render>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="detailId"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="action" slot-scope="text, record">

          <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
          <a-divider type="vertical" />
          <a @click="handleDetail(record)">详情</a>
            </span>

          </a-table>
        </a-tab-pane>
      </a-tabs>

    <crm-production-plan-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import CrmProductionPlanModal from './modules/CrmProductionPlanModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import '@/assets/less/TableExpand.less'
  import {deleteAction, getAction, postAction} from "@api/manage";
  import {filterObj} from "@/utils/util";
  import ActApplyBtn from '@views/flowable/components/ActApplyBtn.vue'
  import ActCancelBtn from '@views/flowable/components/ActCancelBtn.vue'
  import ActHandleBtn from '@views/flowable/components/ActHandleBtn.vue'
  import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'
  import {stopProcess} from "@views/flowable/api/process";

  export default {
    name: "CrmProductionPlanList",
    mixins:[JeecgListMixin],
    components: {
      CrmProductionPlanModal,
      ActApplyBtn,
      ActCancelBtn,
      ActHandleBtn,
      ActHistoricDetailBtn,
    },
    data () {
      return {
        description: '生产计划单管理页面',
        activeKey:'cg',
        serviceName: 'productionPlanService',
        table1: {
          selectedRowKeys: [],
          selectionRows: [],
          loading: false,
          columns: [
            {
              title: '#',
              dataIndex: '',
              key: 'rowIndex',
              width: 60,
              align: 'center',
              customRender: function (t, r, index) {
                return parseInt(index) + 1
              },
            },
            {
              title: '单据类型',
              align: 'center',
              dataIndex: 'documentType_dictText',
            },
            {
              title: '订单编号',
              align: 'center',
              dataIndex: 'schedulingNumber',
            },
            {
              title: '销售类型',
              align: 'center',
              dataIndex: 'salesType_dictText',
            },
            {
              title: '业务类型',
              align: 'center',
              dataIndex: 'contractBusinessType_dictText',
            },
            {
              title: '制单人',
              align: 'center',
              dataIndex: 'createBy_dictText',
            },
            {
              title: '制单部门',
              align: 'center',
              dataIndex: 'sysOrgCode_dictText',
            },
            {
              title: '制单时间',
              align: 'center',
              dataIndex: 'createTime',
              sorter: (a, b) => a.createTime.localeCompare(b.createTime, 'en'),
            },
          ],
          dataSource: [],
          isorter: {
            column: 'createTime',
            order: 'desc',
          },
          ipagination: {
            current: 1,
            pageSize: 20,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0,
          },
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'营销生产计划单号',
            align:"center",
            dataIndex: 'planCode'
          },
          {
            title:'单据类型',
            align:"center",
            dataIndex: 'documentType_dictText'
          },
          {
            title:'订单编号',
            align:"center",
            dataIndex: 'schedulingNumber'
          },
          {
            title:'销售类型',
            align:"center",
            dataIndex: 'salesType_dictText'
          },
          {
            title:'业务类型',
            align:"center",
            dataIndex: 'contractBusinessType_dictText'
          },
          {
            title:'是否开启',
            align:"center",
            dataIndex: 'onOff_dictText'
          },
          {
            title: '制单人',
            align: 'center',
            dataIndex: 'createBy_dictText',
          },
          {
            title: '制单部门',
            align: 'center',
            dataIndex: 'sysOrgCode_dictText',
          },
          {
            title: '制单时间',
            align: 'center',
            dataIndex: 'createTime',
            sorter: (a, b) => a.createTime.localeCompare(b.createTime, 'en'),
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/productionplan/crmProductionPlan/listDetail",
          delete: "/productionplan/crmProductionPlan/delete",
          deleteBatch: "/productionplan/crmProductionPlan/deleteBatch",
          exportXlsUrl: "/productionplan/crmProductionPlan/exportXls",
          importExcelUrl: "productionplan/crmProductionPlan/importExcel",
          noOrderGenerated:"/productionplan/crmProductionPlan/noOrderGenerated",
          editMain: '/review/crmTradeOrder/editMain',
          editMainPlan: '/productionplan/crmProductionPlan/editMain',
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      handleDelete: function (id) {
        if (!this.url.delete) {
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            //重新计算分页问题
            that.reCalculatePage(1)
            that.$message.success(res.message);
            that.modalFormOk();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      openButton(record,code){
        if (this.table1.selectionRows.length == 0) {
          this.$message.warn('请选择订单！')
          return
        }
        const rows = this.table1.selectionRows[0]
        rows[record] = code
        postAction(this.url.editMain,rows).then((res)=>{
          if(res.code==200){
            this.$message.success(res.message);
            // that.$emit('ok');
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.handleChangeTab()
        })

      },
      openPlanButton(record,code){
        if (this.selectionRows.length == 0) {
          this.$message.warn('请选择一条记录！')
          return
        }
        const rows = this.selectionRows[0]
        rows[record] = code
        postAction(this.url.editMainPlan,rows).then((res)=>{
          if(res.code==200){
            this.$message.success(res.message);
            // that.$emit('ok');
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.handleChangeTab()
        })

      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
        console.log(this.selectedRowKeys,this.selectionRows)

      },
      handleStop(row) {
        const params = {
          instanceId: row.processInstanceId,
        }
        stopProcess(params).then((res) => {
          this.$message.success(res.message)
          this.handleChangeTab()
        })
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        switch (this.activeKey) {
          case 'cg':
            this.loadData(0,999)
            break
          case 'notGenerated':
            this.loadData(0,-2)
            break
          case 'needEdit':
            this.loadData(0,-1)
            break
          case 'approving':
            this.loadData(0,0)
            break
          case 'approved':
            this.loadData(0,999)
            break
          default:
            break
        }
        //清空列表选中
        this.onClearSelected()
      },
      onClearSelected() {
        this.table1.selectedRowKeys = [];
        this.table1.selectionRows = [];
      },
      handleAdd(){
        if(this.table1.selectionRows.length<=0) {
          this.$message.warning('请选择一条记录！');
          return;
        }
          this.$refs.modalForm.add(this.table1.selectionRows);
          this.$refs.modalForm.title = "新增";
          this.$refs.modalForm.disableSubmit = false;

      },
      handleChangeTab() {
        switch (this.activeKey) {
          case 'cg':
            this.loadData(1,999)
            break
          case 'notGenerated':
            this.loadData(1,-2)
            break
          case 'needEdit':
            this.loadData(1,-1)
            break
          case 'approving':
            this.loadData(1,0)
            break
          case 'approved':
            this.loadData(1,999)
            break
          default:
            break
        }
      },
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        switch (this.activeKey) {
          case 'notGenerated':
            this.loadData(0,-2)
            break
          case 'needEdit':
            this.loadData(0,-1)
            break
          case 'approving':
            this.loadData(0,0)
            break
          case 'approved':
            this.loadData(0,999)
            break
          default:
            break
        }
      },
      getQueryParams() {
        //获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
        // param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      loadData(arg,status) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        params.status = status
        params.salesType = 1

        if(this.activeKey=='cg'){
          this.table1.loading = true
          getAction(this.url.noOrderGenerated, params).then((res) => {
            if (res.success) {
              //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
              this.table1.dataSource = res.result.records || res.result;
              this.dataSourceBack=this.dataSource
              if (res.result.total) {
                this.ipagination.total = res.result.total;
              } else {
                this.ipagination.total = 0;
              }
              //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            this.table1.loading = false
          })
        }else {
          this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result;
            this.dataSourceBack=this.dataSource
            if (res.result.total) {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
        }
      },
      handleTableChange1(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.table1.isorter.column = sorter.field;
          this.table1.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.table1.ipagination = pagination;
        this.loadData(0,999);
      },
      onSelectChangeTab1(selectedRowKeys, selectionRows) {
        this.table1.selectedRowKeys = selectedRowKeys
        this.table1.selectionRows = selectionRows
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'planCode',text:'营销生产计划单号',dictCode:''})
        fieldList.push({type:'string',value:'flowflag',text:'审批流程',dictCode:'plan_flow_flag'})
        fieldList.push({type:'Text',value:'description',text:'特殊说明',dictCode:''})
        fieldList.push({type:'string',value:'salesType',text:'销售类型',dictCode:'sales_type'})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>